package com.dal.common.utils;

import java.io.*;
import java.util.*;
import java.util.regex.*;

public class EnhancedTxtParser {
    public static void main(String[] args) throws Exception {
        String filePath = "/Users/jian/Desktop/registry/1.txt";
        String content = readFileContent(filePath);
        List<Map<String, Object>> dataList = new ArrayList<>();
        Set<String> fields = new LinkedHashSet<>();
        Map<String, String> fieldTypes = new HashMap<>();

        // 解析完整内容
        parseContent(content, dataList, fields, fieldTypes);

        // 显示解析结果统计
        System.out.println("成功解析记录数: " + dataList.size());
        System.out.println("发现字段数量: " + fields.size());

        // 生成插入语句（示例输出前5条）
        List<String> insertSqls = generateConcreteInsertSql(dataList, fields, "data_table");
        System.out.println("\n生成的首批插入语句：");
        insertSqls.stream().limit(5).forEach(System.out::println);
    }

    private static String readFileContent(String filePath) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
        }
        return sb.toString();
    }

    private static void parseContent(String content, List<Map<String, Object>> dataList,
                                     Set<String> fields, Map<String, String> fieldTypes) {
        // 修正后的正则表达式
        Pattern objectPattern = Pattern.compile("\\{(.*?)\\}", Pattern.DOTALL);
        Pattern fieldPattern = Pattern.compile(
                "(\\w+)\\s*:\\s*" +
                        "(?:" +
                        "'((?:[^'\\\\]|\\\\.)*)'|" +     // 单引号字符串（支持转义）
                        "\"([^\"]*)\"|" +                // 双引号字符串
                        "(\\d+\\.?\\d*)|" +              // 数字（整数或小数）
                        "(true|false)|" +                // 布尔值
                        "(null)" +                       // null值
                        ")",
                Pattern.CASE_INSENSITIVE | Pattern.DOTALL);

        Matcher objectMatcher = objectPattern.matcher(content);
        while (objectMatcher.find()) {
            Map<String, Object> row = new HashMap<>();
            String objectContent = objectMatcher.group(1);

            Matcher fieldMatcher = fieldPattern.matcher(objectContent);
            while (fieldMatcher.find()) {
                String key = fieldMatcher.group(1);
                String singleQuoteValue = fieldMatcher.group(2);
                String doubleQuoteValue = fieldMatcher.group(3);
                String numValue = fieldMatcher.group(4);
                String boolValue = fieldMatcher.group(5);
                String nullValue = fieldMatcher.group(6);

                // ...（后续处理逻辑保持不变）
            }
            if (!row.isEmpty()) {
                dataList.add(row);
            }
        }
    }
    private static void parseContent1(String content, List<Map<String, Object>> dataList,
                                    Set<String> fields, Map<String, String> fieldTypes) {
        // 匹配整个对象结构的正则表达式
        Pattern objectPattern = Pattern.compile("\\{(.*?)\\}", Pattern.DOTALL);
        Matcher objectMatcher = objectPattern.matcher(content);

        // 字段解析正则表达式（增强版）
        Pattern fieldPattern = Pattern.compile(
            "(\\w+)\\s*:\\s*" +
            "(?:'((?:[^'\\\\]|\\\\.)*)')" +  // 单引号字符串（支持转义）
            "|(\"[^\"]*\")" +               // 双引号字符串 
            "|(\\d+\\.?\\d*)" +             // 数字（支持小数）
            "|(true|false)" +               // 布尔值
            "|(null))",                     // null值
            Pattern.CASE_INSENSITIVE);

        while (objectMatcher.find()) {
            Map<String, Object> row = new HashMap<>();
            String objectContent = objectMatcher.group(1);
            
            Matcher fieldMatcher = fieldPattern.matcher(objectContent);
            while (fieldMatcher.find()) {
                String key = fieldMatcher.group(1);
                String strValue = fieldMatcher.group(2);
                String dblQuoteValue = fieldMatcher.group(3);
                String numValue = fieldMatcher.group(4);
                String boolValue = fieldMatcher.group(5);
                String nullValue = fieldMatcher.group(6);

                Object value = null;
                String type = "String";

                if (strValue != null) {
                    value = strValue.replace("\\'", "'");
                } else if (dblQuoteValue != null) {
                    value = dblQuoteValue.substring(1, dblQuoteValue.length()-1);
                } else if (numValue != null) {
                    if (numValue.contains(".")) {
                        value = Double.parseDouble(numValue);
                        type = "Double";
                    } else {
                        value = Long.parseLong(numValue);
                        type = "Long";
                    }
                } else if (boolValue != null) {
                    value = Boolean.parseBoolean(boolValue);
                    type = "Boolean";
                } else if (nullValue != null) {
                    value = null;
                }

                if (value != null) {
                    row.put(key, value);
                    if (!fieldTypes.containsKey(key)) {
                        fieldTypes.put(key, type);
                        fields.add(key);
                    }
                }
            }
            if (!row.isEmpty()) {
                dataList.add(row);
            }
        }
    }

    private static List<String> generateConcreteInsertSql(List<Map<String, Object>> dataList,
                                                         Set<String> fields, 
                                                         String tableName) {
        List<String> sqlList = new ArrayList<>();
        for (Map<String, Object> row : dataList) {
            StringBuilder fieldsSb = new StringBuilder();
            StringBuilder valuesSb = new StringBuilder();
            
            for (String field : fields) {
                // 处理字段名
                if (fieldsSb.length() > 0) fieldsSb.append(", ");
                fieldsSb.append(field);
                
                // 处理字段值
                Object value = row.get(field);
                
                if (valuesSb.length() > 0) valuesSb.append(", ");
                if (value == null) {
                    valuesSb.append("NULL");
                } else {
                    String sqlValue;
                    if (value instanceof String) {
                        sqlValue = "'" + value.toString().replace("'", "''") + "'";
                    } else if (value instanceof Boolean) {
                        sqlValue = (Boolean)value ? "1" : "0";
                    } else if (value instanceof Double) {
                        sqlValue = String.format("%.4f", value);
                    } else {
                        sqlValue = value.toString();
                    }
                    valuesSb.append(sqlValue);
                }
            }
            
            sqlList.add(String.format("INSERT INTO %s (%s)\nVALUES (%s);", 
                     tableName, 
                     fieldsSb.toString(),
                     valuesSb.toString()));
        }
        return sqlList;
    }
}